/**
 * @file log_custom.cpp
 *
 * Copyright (C) 2025. Huawei Technologies Co., Ltd. All rights reserved.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 */
#include "celu_custom_tiling.h"
#include "kernel_operator.h"

constexpr int32_t BUFFER_NUM = 2; // tensor num for each queue

constexpr uint32_t BFLOAT16 = 0;
constexpr uint32_t FLOAT16 = 1;
constexpr uint32_t FLOAT32 = 2;
constexpr uint32_t INT8 = 3;
constexpr uint32_t INT16 = 4;
constexpr uint32_t INT32 = 5;

constexpr uint32_t LAST_TWO_TILE = 2;

template <typename dataType> class KernelCELU;

template <> class KernelCELU<half> {
public:
    __aicore__ inline KernelCELU() {}
    __aicore__ inline void Init(GM_ADDR x, GM_ADDR z, float negativeSlope, CELUCustomTilingData tiling)
    {
        this->negativeSlope = static_cast<float>(negativeSlope);
        if (tiling.isEvenCore)
        {
            this->blockLength = tiling.blockLength;
            this->tileNum = tiling.tileNum;
            this->tileLength = tiling.tileLength / BUFFER_NUM;
            this->lastTileLength = tiling.lastTileLength;

            xGm.SetGlobalBuffer((__gm__ half *)x + this->blockLength * AscendC::GetBlockIdx(), this->blockLength);
            zGm.SetGlobalBuffer((__gm__ half *)z + this->blockLength * AscendC::GetBlockIdx(), this->blockLength);
        }
        else
        {
            if (AscendC::GetBlockIdx() < tiling.formerNum)
            {
                this->tileNum = tiling.formerTileNum;
                this->tileLength = tiling.formerTileLength / BUFFER_NUM;
                this->lastTileLength = tiling.formerLastTileLength;

                xGm.SetGlobalBuffer((__gm__ half *)x + tiling.formerLength * AscendC::GetBlockIdx(),
                                    tiling.formerLength);
                zGm.SetGlobalBuffer((__gm__ half *)z + tiling.formerLength * AscendC::GetBlockIdx(),
                                    tiling.formerLength);
            }
            else
            {
                this->tileNum = tiling.tailTileNum;
                this->tileLength = tiling.tailTileLength / BUFFER_NUM;
                this->lastTileLength = tiling.tailLastTileLength;

                xGm.SetGlobalBuffer((__gm__ half *)x + tiling.formerLength * tiling.formerNum +
                                        tiling.tailLength * (AscendC::GetBlockIdx() - tiling.formerNum),
                                    tiling.tailLength);
                zGm.SetGlobalBuffer((__gm__ half *)z + tiling.formerLength * tiling.formerNum +
                                        tiling.tailLength * (AscendC::GetBlockIdx() - tiling.formerNum),
                                    tiling.tailLength);
            }
        }
        pipe.InitBuffer(inQueueX, BUFFER_NUM, this->tileLength * sizeof(half));
        pipe.InitBuffer(outQueueZ, BUFFER_NUM, this->tileLength * sizeof(half));
        pipe.InitBuffer(tmpBuf0, this->tileLength * sizeof(float));
        pipe.InitBuffer(tmpBuf1, this->tileLength * sizeof(float));
    }
    __aicore__ inline void Process()
    {
        int32_t loopCount = this->tileNum * BUFFER_NUM;
        for (int32_t i = 0; i < loopCount; i++)
        {
            CopyIn(i);
            Compute(i);
            CopyOut(i);
        }
    }

private:
    __aicore__ inline void CopyIn(int32_t progress)
    {
        AscendC::LocalTensor<half> xLocal = inQueueX.AllocTensor<half>();
        if ((progress == (this->tileNum * BUFFER_NUM - 2)) || (progress == (this->tileNum * BUFFER_NUM - 1)))
        {
            AscendC::DataCopy(xLocal, xGm[(progress - LAST_TWO_TILE) * this->tileLength + this->lastTileLength],
                              this->tileLength);
        }
        else
        {
            AscendC::DataCopy(xLocal, xGm[progress * this->tileLength], this->tileLength);
        }
        inQueueX.EnQue(xLocal);
    }
    __aicore__ inline void Compute(int32_t progress)
    {
        AscendC::LocalTensor<half> xLocal = inQueueX.DeQue<half>();
        AscendC::LocalTensor<half> zLocal = outQueueZ.AllocTensor<half>();
        AscendC::LocalTensor<float> tmptensor0 = tmpBuf0.Get<float>();
        AscendC::LocalTensor<float> tmptensor1 = tmpBuf1.Get<float>();

        AscendC::Cast(tmptensor0, xLocal, AscendC::RoundMode::CAST_NONE, this->tileLength);
        AscendC::Maxs(tmptensor1, tmptensor0, (float)0.0, this->tileLength);  // max(0,x)

        AscendC::Muls(tmptensor0, tmptensor0, (float)1.0/this->negativeSlope, this->tileLength); // x/a
        AscendC::Exp(tmptensor0, tmptensor0, this->tileLength);                     // exp(x/a)
        AscendC::Adds(tmptensor0, tmptensor0, -(float)1.0, this->tileLength); // exp(x/a)-1
        AscendC::Muls(tmptensor0, tmptensor0, this->negativeSlope, this->tileLength); // a(exp(x/a)-1)
        AscendC::Mins(tmptensor0, tmptensor0, (float)0.0, this->tileLength);  // min(0,a(exp(x/a)-1))

        AscendC::Add(tmptensor1, tmptensor0, tmptensor1, this->tileLength);  // max(0,x) + min(0,a(exp(x/a)-1))
        AscendC::Cast(zLocal, tmptensor1, AscendC::RoundMode::CAST_NONE, this->tileLength);

        outQueueZ.EnQue<half>(zLocal);
        inQueueX.FreeTensor(xLocal);
    }
    __aicore__ inline void CopyOut(int32_t progress)
    {
        AscendC::LocalTensor<half> zLocal = outQueueZ.DeQue<half>();
        if ((progress == (this->tileNum * BUFFER_NUM - 2)) || (progress == (this->tileNum * BUFFER_NUM - 1)))
        {
            AscendC::DataCopy(zGm[(progress - LAST_TWO_TILE) * this->tileLength + this->lastTileLength], zLocal,
                              this->tileLength);
        }
        else
        {
            AscendC::DataCopy(zGm[progress * this->tileLength], zLocal, this->tileLength);
        }
        outQueueZ.FreeTensor(zLocal);
    }

private:
    float negativeSlope;

    AscendC::TPipe pipe;
    AscendC::TQue<AscendC::TPosition::VECIN, BUFFER_NUM> inQueueX;
    AscendC::TQue<AscendC::TPosition::VECOUT, BUFFER_NUM> outQueueZ;

    AscendC::GlobalTensor<half> xGm;
    AscendC::GlobalTensor<half> zGm;

    AscendC::TBuf<AscendC::TPosition::VECCALC> tmpBuf0, tmpBuf1;

    uint32_t blockLength;
    uint32_t tileNum;
    uint32_t tileLength;
    uint32_t lastTileLength;
};

template <typename dataType> class KernelCELU {
public:
    __aicore__ inline KernelCELU() {}
    __aicore__ inline void Init(GM_ADDR x, GM_ADDR z, float negativeSlope, CELUCustomTilingData tiling)
    {   
        this->negativeSlope = static_cast<dataType>(negativeSlope);
        if (tiling.isEvenCore)
        {
            this->blockLength = tiling.blockLength;
            this->tileNum = tiling.tileNum;
            this->tileLength = tiling.tileLength / BUFFER_NUM;
            this->lastTileLength = tiling.lastTileLength;

            xGm.SetGlobalBuffer((__gm__ dataType *)x + this->blockLength * AscendC::GetBlockIdx(), this->blockLength);
            zGm.SetGlobalBuffer((__gm__ dataType *)z + this->blockLength * AscendC::GetBlockIdx(), this->blockLength);
        }
        else
        {
            if (AscendC::GetBlockIdx() < tiling.formerNum)
            {
                this->tileNum = tiling.formerTileNum;
                this->tileLength = tiling.formerTileLength / BUFFER_NUM;
                this->lastTileLength = tiling.formerLastTileLength;

                xGm.SetGlobalBuffer((__gm__ dataType *)x + tiling.formerLength * AscendC::GetBlockIdx(),
                                    tiling.formerLength);
                zGm.SetGlobalBuffer((__gm__ dataType *)z + tiling.formerLength * AscendC::GetBlockIdx(),
                                    tiling.formerLength);
            }
            else
            {
                this->tileNum = tiling.tailTileNum;
                this->tileLength = tiling.tailTileLength / BUFFER_NUM;
                this->lastTileLength = tiling.tailLastTileLength;

                xGm.SetGlobalBuffer((__gm__ dataType *)x + tiling.formerLength * tiling.formerNum +
                                        tiling.tailLength * (AscendC::GetBlockIdx() - tiling.formerNum),
                                    tiling.tailLength);
                zGm.SetGlobalBuffer((__gm__ dataType *)z + tiling.formerLength * tiling.formerNum +
                                        tiling.tailLength * (AscendC::GetBlockIdx() - tiling.formerNum),
                                    tiling.tailLength);
            }
        }
        pipe.InitBuffer(inQueueX, BUFFER_NUM, this->tileLength * sizeof(dataType));
        pipe.InitBuffer(outQueueZ, BUFFER_NUM, this->tileLength * sizeof(dataType));
        pipe.InitBuffer(tmpBuf0, this->tileLength * sizeof(dataType));
    }
    __aicore__ inline void Process()
    {
        int32_t loopCount = this->tileNum * BUFFER_NUM;
        for (int32_t i = 0; i < loopCount; i++)
        {
            CopyIn(i);
            Compute(i);
            CopyOut(i);
        }
    }

private:
    __aicore__ inline void CopyIn(int32_t progress)
    {
        AscendC::LocalTensor<dataType> xLocal = inQueueX.AllocTensor<dataType>();
        if ((progress == (this->tileNum * BUFFER_NUM - 2)) || (progress == (this->tileNum * BUFFER_NUM - 1)))
        {
            AscendC::DataCopy(xLocal, xGm[(progress - LAST_TWO_TILE) * this->tileLength + this->lastTileLength],
                              this->tileLength);
        }
        else
        {
            AscendC::DataCopy(xLocal, xGm[progress * this->tileLength], this->tileLength);
        }
        inQueueX.EnQue(xLocal);
    }
    __aicore__ inline void Compute(int32_t progress)
    {
        AscendC::LocalTensor<dataType> xLocal = inQueueX.DeQue<dataType>();
        AscendC::LocalTensor<dataType> zLocal = outQueueZ.AllocTensor<dataType>();
        AscendC::LocalTensor<dataType> tmptensor0 = tmpBuf0.Get<dataType>();
        
        AscendC::Maxs(tmptensor0, xLocal, (dataType)0.0, this->tileLength);  // max(0,x)

        AscendC::Muls(xLocal, xLocal, (dataType)1.0/this->negativeSlope, this->tileLength); // x/a
        AscendC::Exp(xLocal, xLocal, this->tileLength);                     // exp(x/a)
        AscendC::Adds(xLocal, xLocal, -(dataType)1.0, this->tileLength); // exp(x/a)-1
        AscendC::Muls(xLocal, xLocal, this->negativeSlope, this->tileLength); // a(exp(x/a)-1)
        AscendC::Mins(xLocal, xLocal, (dataType)0.0, this->tileLength);  // min(0,a(exp(x/a)-1))

        AscendC::Add(zLocal, tmptensor0, xLocal, this->tileLength);  // max(0,x) + min(0,a(exp(x/a)-1))

        outQueueZ.EnQue<dataType>(zLocal);
        inQueueX.FreeTensor(xLocal);
    }
    __aicore__ inline void CopyOut(int32_t progress)
    {
        AscendC::LocalTensor<dataType> zLocal = outQueueZ.DeQue<dataType>();
        if ((progress == (this->tileNum * BUFFER_NUM - 2)) || (progress == (this->tileNum * BUFFER_NUM - 1)))
        {
            AscendC::DataCopy(zGm[(progress - LAST_TWO_TILE) * this->tileLength + this->lastTileLength], zLocal,
                              this->tileLength);
        }
        else
        {
            AscendC::DataCopy(zGm[progress * this->tileLength], zLocal, this->tileLength);
        }
        outQueueZ.FreeTensor(zLocal);
    }

private:
    dataType negativeSlope;

    AscendC::TPipe pipe;
    AscendC::TQue<AscendC::TPosition::VECIN, BUFFER_NUM> inQueueX;
    AscendC::TQue<AscendC::TPosition::VECOUT, BUFFER_NUM> outQueueZ;

    AscendC::GlobalTensor<dataType> xGm;
    AscendC::GlobalTensor<dataType> zGm;

    AscendC::TBuf<AscendC::TPosition::VECCALC> tmpBuf0;

    uint32_t blockLength;
    uint32_t tileNum;
    uint32_t tileLength;
    uint32_t lastTileLength;
};

extern "C" __global__ __aicore__ void celu_custom(GM_ADDR x, GM_ADDR z, float negativeSlope, CELUCustomTilingData tiling)
{

    if (tiling.dataType == FLOAT32)
    {
        KernelCELU<float> op;
        op.Init(x, z, negativeSlope, tiling);
        op.Process();
    }
    else if (tiling.dataType == FLOAT16)
    {
        KernelCELU<half> op;
        op.Init(x, z, negativeSlope, tiling);
        op.Process();
    }

}
